//
//  WBOAuthViewController.swift
//  ZWWEIBO
//
//  Created by xzw on 2018/4/6.
//  Copyright © 2018年 xzw. All rights reserved.
//

import UIKit
import SVProgressHUD

class WBOAuthViewController: UIViewController {

    private lazy var webView : UIWebView = UIWebView()
    
    override func loadView() {
       view = webView
       webView.scrollView.isScrollEnabled = false
       view.backgroundColor = UIColor.white
        
       //设置delegate
       webView.delegate = self
        
       title = "登陆新浪微博"
       navigationItem.leftBarButtonItem = UIBarButtonItem(title:"返回", target: self, action: #selector(back), isBackButton: true)
       navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFill))
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        loadWebPage()
    }
    
     //MARK: - 加载网页界面
    private func loadWebPage(){
      
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(AppKey)&redirect_uri=\(Redirect_URL)"
        guard let url = URL(string: urlStr) else{
            return
        }
        let request = URLRequest(url: url)
        webView.loadRequest(request)
        
//        let data = try? Data(contentsOf: url)
//        webView.load(data!, mimeType: "text/html", textEncodingName: "UTF-8", baseURL: url)
        
    }
    
     //MARK: - 返回按钮
    @objc private func back(){
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
    }
    
    
     //MARK: - 自动填充登录账号和密码 webview注入，修改浏览器本地缓存的数据
    @objc private func autoFill(){
        
        //1.准备js
        let js = "document.getElementById('userId').value = '13076997690';" + "document.getElementById('passwd').value = 'xzw2007519';"
        
        //2.webview执行js
        webView.stringByEvaluatingJavaScript(from: js)
        
    }
}

 //MARK: -
extension WBOAuthViewController : UIWebViewDelegate{
    
    //准备加载webview请求
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //print("加载请求 \(request)")
        
        //1.如果请求url中包括‘http://baidu.com’则不加在改请求
        if request.url?.absoluteString.hasPrefix(Redirect_URL) == false {
            return true
        }
        
        //2.查找url中包括‘https://www.baidu.com/?code=4eed1c690a1a295c1c2c4d6973ade4d3’
        //query:获取url ? 后面所有字符串
        if request.url?.query?.hasPrefix("code=") == false {
            //print("取消授权")
            back() //返回
            return false
        }
        
        //3.获取code let newStr = str[..<index]  let newStr = str[index...]  swift4.0
        // let code = request.url?.query?.substring(from: "code=".endIndex) ?? "" //swift3.0
        
       guard let querystr = request.url?.query else{
             return false
        }
        
        let subCode = querystr["code=".endIndex...]
        let code = String(describing: subCode)
        print(code)
        
        //4.用code请求accessToken
        WBNetworkManager.sharedInstance.getAcessToken(code: code) { (issuccess) in
            if !issuccess
            {
                SVProgressHUD.showInfo(withStatus: "获取toToken失败")
            }else
            {
                //SVProgressHUD.showInfo(withStatus: "获取toToken成功")
                //发送登录成功通知
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserLoginSuccessNotification), object: nil)
                
                self.back() //返回上一个界面
                
            }
            
        }
        
        return false
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        SVProgressHUD.dismiss()
       // print("网页加载失败 \(error)")
    }
}
